import requests
from func_timeout import func_set_timeout, FunctionTimedOut


class BaiDuFanYi:

    @classmethod
    @func_set_timeout(3)
    def langdetect(self, q):
        url = 'https://fanyi.baidu.com/langdetect'
        headers = {
            'accept': '*/*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'content-length': '54',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cookie': 'BAIDUID=F0FF33B4A471BFB1A787D2A5C880CACD:FG=1; BIDUPSID=F0FF33B4A471BFB1A787D2A5C880CACD; PSTM=1597929064; delPer=0; PSINO=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=7541_32606_1454_7566_31254_7612_32679_7627_32116_31708_26350_32583; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1599973085; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1599973085; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; __yjsv5_shitong=1.0_7_32c407409d3d968c512c21974f1922cbe51e_300_1599973086089_120.244.200.230_33146468; yjs_js_security_passport=bf36ec23d664f80fa335e1d76b4b2e8900423a28_1599973089_js',
            'origin': 'https://fanyi.baidu.com',
            'referer': 'https://fanyi.baidu.com/?aldtype=16047',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
        }
        data = {
            'query': q
        }
        r = requests.post(url=url, data=data, headers=headers)
        res = r.text
        print(res)

    def translate(self, q):
        lang_data = self.langdetect(q)
        if lang_data.get('msg') == 'success':
            lang = lang_data.get('lan')
        else:
            lang = 'en'

        data = {
            'from': lang,
            'to': 'zh',
            'query': q,
            'transtype': 'realtime',
            'simple_means_flag': '3',
            'sign': '676721.962624',
            'token': '4161352cac9c69ea81bfb04020f207a0',
            'domain': 'common',
        }


if __name__ == "__main__":
    q = 'He is promoted to be the manager of the company.'
    BaiDuFanYi.langdetect(q)
